package com.github.ilioili.justdoit.components.patch;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;

import com.github.ilioili.justdoit.model.to.VersionInfo;

import java.io.File;

/**
 * Created by User on 16/6/22.
 */
public class DownloadHelper {

    protected static void downloadOrInstall(VersionInfo versionInfo, Context context) {
        File dir = new File(Environment.getExternalStorageDirectory() + "/JustDoIt");
        dir.mkdirs();
        String path = Environment.getExternalStorageDirectory() + "/JustDoIt/JustDoIt" + versionInfo.versionName + ".apk";
        final File file = new File(path);
        if (file.exists()) {
            Intent it = new Intent(Intent.ACTION_VIEW);
            it.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            context.startActivity(it);
        } else {
            DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionInfo.apkUrl));
            request.setDestinationInExternalPublicDir("JustDoIt", "JustDoIt" + versionInfo.versionName + ".apk");
            request.setTitle("JustDoIt");
            request.setDescription("Version:" + versionInfo.versionName);
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
            final long downloadId = downloadManager.enqueue(request);
            context.getApplicationContext().registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    long requestId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                    if (requestId == downloadId) {
                        Intent it = new Intent(Intent.ACTION_VIEW);
                        it.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                        it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(it);
                    }
                }
            }, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        }
    }
}
